package com.example.uidemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.uidemo.dto.Fruit;
import com.example.uidemo.adapter.FruitAdapter;

import java.util.ArrayList;
import java.util.List;

public class ListViewDemo extends AppCompatActivity {

    private String[] data = {"apple", "banana", "orange", "watermelon", "pear", "Grape", "apple", "banana", "orange", "watermelon", "pear", "Grape", "apple", "banana", "orange", "watermelon", "pear", "Grape", "apple", "banana", "orange", "watermelon", "pear", "Grape", "apple", "banana", "orange", "watermelon", "pear", "Grape"};

    private List<Fruit> fruitList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_view_demo);

        /**
         * 简单的ListView
         */
    /*    ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<String>(ListViewDemo.this,android.R.layout.simple_list_item_1,data);
        ListView viewById = (ListView) findViewById(R.id.list_view);
        viewById.setAdapter(stringArrayAdapter);*/

        /**
         * 自定义ListView
         */
        initFruits(); // 初始化数据
        FruitAdapter adapter = new FruitAdapter(ListViewDemo.this,R.layout.fruit_item,fruitList);  // 设置适配器
        ListView listView = (ListView) findViewById(R.id.list_view);  // 获取ListView
        listView.setAdapter(adapter);   // 把适配器装到ListView里
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {  // item点击监听
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Fruit fruit = fruitList.get(position);
                Toast.makeText(ListViewDemo.this,fruit.getName(),Toast.LENGTH_LONG).show();
            }
        });

    }

    public  void initFruits(){
        for (int i=0,j =data.length;i<j;i++){
            Fruit f = new Fruit(data[i],R.drawable.apple);
            fruitList.add(f);
            Fruit d = new Fruit(data[i],R.drawable.banana);
            fruitList.add(d);
        }
    }

}
